package com.p7.notepad.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.p7.notepad.R;
import com.p7.notepad.activity.LoginActivity;
import com.p7.notepad.activity.MainActivity;
import com.p7.notepad.activity.PwdActivity;
import com.p7.notepad.activity.RecycleActivity;
import com.p7.notepad.activity.SwitchUserActivity;
import com.p7.notepad.activity.UresActivity;
import com.p7.notepad.app.BaseFragment;
import com.p7.notepad.app.MyApplication;
import com.p7.notepad.bean.Success;
import com.p7.notepad.network.APIManager;
import com.p7.notepad.network.exception.ExceptionHandle;
import com.p7.notepad.network.listener.RequestListener;
import com.p7.notepad.tools.FileUtils;
import com.p7.notepad.tools.ImageUtils;
import com.p7.notepad.tools.PhotoUtils;
import com.p7.notepad.tools.Storage;
import com.widget.s7.widget.CircleImageView;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class MeFragment extends BaseFragment implements CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.me_image)
    CircleImageView mImage;
    @BindView(R.id.me_name)
    TextView mName;
    @BindView(R.id.me_mode)
    CheckBox mMode;
    @BindView(R.id.me_btn)
    LinearLayout mBtns;

    private PhotoUtils photoUtils;

    public MeFragment() {
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_me;
    }

    @Override
    protected void initEvents() {
        mMode.setChecked(Storage.getMode());
        mMode.setOnCheckedChangeListener(this);

        photoUtils = new PhotoUtils();
        photoUtils.setWith(this).setListener(new PhotoUtils.OnPhotoListener() {
            @Override
            public void onPhotoStart() {
            }
            @Override
            public void onPhotoPath(String imagePath) {
                APIManager.uploadFile("file/uploadFile", imagePath, new RequestListener() {
                    @Override
                    public void onSuccess(String s) {
                        Gson gson = new Gson();
                        Success success = gson.fromJson(s, Success.class);
                        if (success.getCode() == 1000) {
                            updateAvatar((String) success.getData());
                        } else if(success.getCode() == 2001) {
                            startActivity(LoginActivity.class);
                        } else {
                            setToast(success.getMessage());
                        }
                    }
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable error) {
                        setToast(error.message);
                    }
                }, null);

            }
            @Override
            public void onPhotoError(String error) {
                setToast(error);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        mName.setText(Storage.getName());
        MyApplication.getInstance().setImage(Storage.getImage(), mImage);
    }

    @OnClick({R.id.me_image, R.id.me_recycle, R.id.me_user, R.id.me_pwd, R.id.me_switch, R.id.me_logout,
            R.id.me_phone, R.id.me_album, R.id.me_cancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.me_image:  // 修改头像
                mBtns.setVisibility(View.VISIBLE);
                break;
            case R.id.me_recycle: // 回收站
                startActivity(RecycleActivity.class);
                break;
            case R.id.me_user: // 修改资料
                startActivity(UresActivity.class);
                break;
            case R.id.me_pwd: // 修改密码
                startActivity(PwdActivity.class);
                break;
            case R.id.me_switch: // 切换账户
                startActivity(SwitchUserActivity.class);
                break;
            case R.id.me_logout: // 退出登录
                Storage.onLogout();
                startActivity(LoginActivity.class);
                ((MainActivity) getActivity()).finish();
                break;
            case R.id.me_phone: // 拍照
                photoUtils.onCamera();
                mBtns.setVisibility(View.GONE);
                break;
            case R.id.me_album: // 相册
                photoUtils.onPhoto();
                mBtns.setVisibility(View.GONE);
                break;
            case R.id.me_cancel: // 取消
                mBtns.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        MyApplication.getInstance().updateNightMode(isChecked);
        Bundle bundle = new Bundle();
        bundle.putInt("page", 3);
        startActivity(getActivity().getClass(), bundle);
        getActivity().finish();
        getActivity().overridePendingTransition(0, 0);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        photoUtils.onActivityResult(getActivity(), requestCode, resultCode, data);
    }

    private void initBitmap(Bitmap photo) {
        Bitmap bitmap = ImageUtils.compressBitmap(photo);
        String name = FileUtils.getPhotoName();
        String path = FileUtils.getPhotoPath();
        String imagePath = path +  "/" + name + FileUtils.IMAGE_FORMAT;
        FileUtils.savePhotoToSDCard(bitmap, path, name);
        APIManager.uploadFile("file/uploadFile", imagePath, new RequestListener() {
            @Override
            public void onSuccess(String s) {
                Gson gson = new Gson();
                Success success = gson.fromJson(s, Success.class);
                if (success.getCode() == 1000) {
                    updateAvatar((String) success.getData());
                } else if(success.getCode() == 2001) {
                    startActivity(LoginActivity.class);
                } else {
                    setToast(success.getMessage());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponeThrowable error) {
                setToast(error.message);
            }
        }, null);
    }

    private void updateAvatar(final String path) {
        Map<String, String> parameters = new HashMap<>();
        parameters.put("id", String.valueOf(Storage.getId()));
        parameters.put("avatar", path);
        APIManager.onPost("user/updateInfo", parameters, new RequestListener() {
            @Override
            public void onSuccess(String s) {
                Gson gson = new Gson();
                Success success = gson.fromJson(s, Success.class);
                if (success.getCode() == 1000) {
                    setToast("图片上传成功");
                    Storage.putImage(path);
                    Storage.putUserUrl(Storage.getId(), path);
                    MyApplication.getInstance().setImage(Storage.getImage(), mImage);
                } else if (success.getCode() == 2001) {
                    startActivity(LoginActivity.class);
                } else {
                    setToast(success.getMessage());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponeThrowable error) {
                setToast(error.message);
            }
        });
    }

    private void setToast(String str) {
        Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
    }
}
